package com.yoomiito.app.ui.order.sureorder.singleGoods;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.GradientDrawable;
import android.os.Bundle;
import android.text.InputFilter;
import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.jakewharton.rxbinding3.view.RxView;
import com.yoomiito.app.base.App;
import com.yoomiito.app.base.BaseActivity;
import com.yoomiito.app.Constant;
import com.yoomiito.app.R;
import com.yoomiito.app.interf.BaseOrderGoodsView;
import com.yoomiito.app.model.bean.AddressInfo;
import com.yoomiito.app.model.bean.AppInterfaceInfo;
import com.yoomiito.app.model.bean.GoodsDetail;
import com.yoomiito.app.model.bean.GoodsList;
import com.yoomiito.app.model.my.MyRemainMoneyInfo;
import com.yoomiito.app.ui.anyview.order.BaoPinPinOrderGoodsView;
import com.yoomiito.app.ui.anyview.order.GiftOrderGoodsView;
import com.yoomiito.app.ui.anyview.order.ShowAddressView;
import com.yoomiito.app.ui.anyview.order.StarStoreGoodsOrderView;
import com.yoomiito.app.ui.anyview.order.YouPinOrderGoodsView;
import com.yoomiito.app.ui.my.psw.SetPayPswActivity;
import com.yoomiito.app.ui.order.list.OrderActivity;
import com.yoomiito.app.ui.order.sureorder.BuyResultActivity;
import com.yoomiito.app.ui.order.UseCouponDialog;
import com.yoomiito.app.utils.Const;
import com.yoomiito.app.utils.DensityUtil;
import com.yoomiito.app.utils.RouterUtils;
import com.yoomiito.app.utils.Type;
import com.yoomiito.app.utils.encrypt.AESUtils;
import com.yoomiito.app.utils.AllCode;
import com.yoomiito.app.utils.AllUtils;
import com.yoomiito.app.utils.EventMessage;
import com.yoomiito.app.utils.L;
import com.yoomiito.app.utils.ResUtil;
import com.yoomiito.app.utils.inputfilter.TextInputFilter;
import com.yoomiito.app.utils.TouchUtils;
import com.yoomiito.app.utils.UserInfoConfig;
import com.yoomiito.app.utils.YMToast;
import com.yoomiito.app.widget.PasswordView_1;
import com.yoomiito.app.widget.TipDialog;
import com.yoomiito.app.widget.dialog.AlipayH5Dialog;
import com.yoomiito.app.widget.dialog.PayDialog;
import com.yoomiito.app.widget.dialog.PswInputDialog;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.OnClick;
import cn.droidlover.xdroidmvp.cache.SharedPref;

/**
 * 确认订单
 */
@Deprecated
public class BuyGoodsActivity extends BaseActivity<BuyGoodsPresenter> {

    @BindView(R.id.act_buy_goods_notes)
    EditText notesTv;
    @BindView(R.id.act_buy_goods_coupon_value)
    TextView couponValueTv;
    @BindView(R.id.act_buy_goods_money)
    TextView mPayPriceTv;
    @BindView(R.id.act_buy_goods_ll)
    LinearLayout parentView;
    @BindView(R.id.goods_container)
    FrameLayout goodsParentView;
    @BindView(R.id.address_container)
    FrameLayout addressParentView;
    @BindView(R.id.act_buy_goods_btn)
    Button mBuyBtn;
    @BindView(R.id.tv_tips)
    TextView mTvTips;
    private GoodsDetail mGoodsDetail;
    private AddressInfo mAddressInfo;
    public String mPayOrderId;
    public String mQueryOrderID;
    public String mPayMoney;//应付金额  来自于服务器
    private int mGoodsType;
    private int goodsSize = 1;
    private String eventId = "";
    private PayDialog payDialog;
    private String mGoodsTotalPrice;//商品总额 显示用
    private String mBalance;//余额
    public String pay_type;//支付类型
    private PswInputDialog pswInputDialog;
    public MyRemainMoneyInfo mMoneyInfo;
    private BaseOrderGoodsView mBaseOrderGoodsView;
    private ShowAddressView mShowAddressView;
    private int yoMoneyPay = 0;//1优币抵扣，0不抵扣
    private AppInterfaceInfo appInterfaceInfo;


    public static void start(Context context, GoodsDetail goodsDetail, int goodsType) {
        Intent intent = new Intent(context, BuyGoodsActivity.class);
        intent.putExtra(Constant.KEY, goodsDetail);
        intent.putExtra(Constant.TYPE, goodsType);
        context.startActivity(intent);
    }

    public static void start(Context context, GoodsDetail goodsDetail, AppInterfaceInfo appInterfaceInfo, int goodsType) {
        Intent intent = new Intent(context, BuyGoodsActivity.class);
        intent.putExtra(Constant.KEY, goodsDetail);
        intent.putExtra(Constant.TYPE, goodsType);
        intent.putExtra("appInterface", appInterfaceInfo);
        context.startActivity(intent);
    }


    @Override
    public int getLayoutId() {
        return R.layout.act_buy_goods_1;
    }

    @Override
    public BuyGoodsPresenter newP() {
        return new BuyGoodsPresenter(App.mAppConfig);
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        super.initData(savedInstanceState);
        mGoodsDetail = (GoodsDetail) getIntent().getSerializableExtra(Constant.KEY);
        mGoodsType = getIntent().getIntExtra(Constant.TYPE, 0);
        appInterfaceInfo = (AppInterfaceInfo) getIntent().getSerializableExtra("appInterface");
        mTvTips.setText(appInterfaceInfo.pickMsg);
        mBalance = appInterfaceInfo.userAccount;
        goodsSize = appInterfaceInfo.againNum;
        switch (mGoodsType) {
            case AllCode.YouPin:
            case AllCode.AgentMall:
                mBaseOrderGoodsView = new YouPinOrderGoodsView(this, mGoodsDetail, appInterfaceInfo);
                showLoading();
                getP().getRemain();
                break;
            case AllCode.BaoPin:
                mBaseOrderGoodsView = new BaoPinPinOrderGoodsView(this, mGoodsDetail, appInterfaceInfo);
                mPayPriceTv.setText(mBaseOrderGoodsView.getSpanText());
                eventId = "hotProductConfirmOrderPagePayClick";
                break;
            case AllCode.Gift:
                mBaseOrderGoodsView = new GiftOrderGoodsView(this, mGoodsDetail, appInterfaceInfo);
                mPayPriceTv.setText(mBaseOrderGoodsView.getSpanText());
                break;
            case Type.GoodsType.GiveMore:
                mBaseOrderGoodsView = new GiftOrderGoodsView(this, mGoodsDetail, appInterfaceInfo);
                mPayPriceTv.setText(mBaseOrderGoodsView.getSpanText());
                eventId = "giftProductConfirmOrderPagePayClick";
                break;
            case AllCode.StarStore:
                mBaseOrderGoodsView = new StarStoreGoodsOrderView(this, mGoodsDetail, appInterfaceInfo);
                mPayPriceTv.setText(mBaseOrderGoodsView.getSpanText());
                break;
        }
        goodsParentView.addView(mBaseOrderGoodsView);
        mBaseOrderGoodsView.addOnShowInfoListener((spanText, goodsSize, yoMoneyPay) -> {
            mPayPriceTv.setText(spanText);
            this.yoMoneyPay = yoMoneyPay;
            if (goodsSize != -1) {
                this.goodsSize = goodsSize;
            }
        });

        notesTv.setFilters(new InputFilter[]{new TextInputFilter(true).setLength(20)});

        getWindow().setSoftInputMode(
                WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        GradientDrawable drawable = (GradientDrawable) mBuyBtn.getBackground();
        drawable.setCornerRadius(DensityUtil.dp2px(23));
        RxView.clicks(mBuyBtn)
                .throttleFirst(1, TimeUnit.SECONDS)
                .subscribe(unit -> {
                    if (appInterfaceInfo.address == 1 && (mAddressInfo == null || TextUtils.isEmpty(mAddressInfo.getId()))) {
                        TouchUtils.onBuyEvent(eventId, UserInfoConfig.getRoleId(), UserInfoConfig.getAgent(), "empty_address");
                        showToast("请添加地址");
                        return;
                    }
                    showPayDialog();
                });
        showLoading();
        getP().getAddress();
    }


    @OnClick({R.id.act_buy_goods_coupon, R.id.act_buy_goods_back})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.act_buy_goods_back:
                finish();
                break;
            case R.id.act_buy_goods_coupon://获取优惠券
                showCouponDialog();
                break;
//            case R.id.act_buy_goods_btn:
//                L.i("点击");
//                if (AllUtils.isFastClick()) {
//                    YMToast.showText("请勿重复点击");
//                    return;
//                }
//                if (mAddressInfo == null) {
//                    TouchUtils.onBuyEvent(eventId, UserInfoConfig.getRoleId(), UserInfoConfig.getAgent(), "empty_address");
//                    showToast("请添加地址");
//                    return;
//                }
//                showLoading();
//                createOrder();
//                //埋点
//                break;

        }
    }

    //获取到微信结果后 查询订单状态

    @Override
    public void eventMessage(EventMessage eventMessage) {
        super.eventMessage(eventMessage);
        if (Constant.PAY_RESULT.equals(eventMessage.getEventType())) {
            if (TextUtils.isEmpty(mQueryOrderID)) {
                showToast("订单状态异常");
                return;
            }
            showLoading();
            payResult(eventMessage);

//            getP().queryOrder(mQueryOrderID, pay_type);
        }
    }

    public void setYouMi(MyRemainMoneyInfo moneyInfo) {
        this.mMoneyInfo = moneyInfo;
        if (moneyInfo.isShowYoumi()) {//只有刚进入订单页面第一次获取时才设置优米  生成订单获取余额时不设置优米
            mBaseOrderGoodsView.setMoneyInfo(mMoneyInfo);
        }
    }

    public void showAddressView(AddressInfo addressInfo) {
        if (appInterfaceInfo.address == 1) {
            addressParentView.setVisibility(View.VISIBLE);
        } else {
            addressParentView.setVisibility(View.GONE);
        }
        dismissLoading();
        mShowAddressView = new ShowAddressView(this);
        addressParentView.addView(mShowAddressView);
        mAddressInfo = addressInfo;
        if (mAddressInfo != null && mAddressInfo.getId() != null) {
            mShowAddressView.setAddressInfo(mAddressInfo);
            mShowAddressView.showAddress();
        }
    }

    //支付弹窗
    public void showPayDialog() {
        dismissLoading();
        if(AllUtils.moneyCompare1(appInterfaceInfo.buyMoneyMin,mBaseOrderGoodsView.mGoodsTotalPrice)){
            YMToast.showText("单笔购买金额不能小于"+appInterfaceInfo.buyMoneyMin+"元");
            return;
        }
        if (payDialog == null) {
            payDialog = new PayDialog(this);
            payDialog.setOnResultListener((moneyPay, wxPay, aliPay, offline,quick, dismiss) -> {
                if (dismiss) {
                    return;
                }
                if (moneyPay == 0 && wxPay == 0 && aliPay == 0 && offline == 0 && quick == 0) {
                    YMToast.showText("请选择付款通道");
                    return;
                }
                if(moneyPay == 1  && wxPay == 0 && aliPay == 0 && AllUtils.moneyCompare1(mBaseOrderGoodsView.mGoodsTotalPrice,mBalance)){
                    YMToast.showText("您的余额不足够本次支付!");
                    return;
                }
                payDialog.dismiss();
                showLoading();
                int payType = 0;
                if (moneyPay == 1 && wxPay == 0 && aliPay == 0 && offline == 0 && quick == 0) {
                    payType = 3;
                } else {
                    if (wxPay == 1) {
                        payType = 1;
                    }
                    if (aliPay == 1) {
                        payType = 2;
                    }
                    if (offline == 1) {
                        payType = 5;
                    }
                    if (wxPay == 1 && moneyPay == 1) {
                        payType = 7;
                    }
                    if (aliPay == 1 && moneyPay == 1) {
                        payType = 6;
                    }
                    if (quick == 1){
                        payType = 8;
                    }
                }

                createOrder(payType);

                //付款方式1-微信，2-支付宝，3-余额支付，5-线下支付,6-支付宝+余额，7-微信+余额
//                if (moneyPay == 1 && wxPay == 0 && aliPay == 0) {
//                    //余额支付 需要密码框
//                    if (UserInfoConfig.havePayPsw()) {
//                        showPsw();
//                    } else {
//                        showSetPswDialog();
//                    }
//                } else {
//                    //非余额支付
//
////
////                    getP().pay(mPayOrderId, wxPay, aliPay, moneyPay == 1 ? mBalance : "0",
////                            mGoodsType == Type.GoodsType.GiveMore ? (mGoodsDetail.getProduct_type() + 1) : mGoodsDetail.getProduct_type(),
////                            "", yoMoneyPay);
//                }

            });
        }
        L.i("支付总价：" + mBaseOrderGoodsView.mGoodsTotalPrice);
        payDialog.setBalance(mBalance);
        payDialog.setShow(appInterfaceInfo);
        payDialog.setPayMoney("¥" + mBaseOrderGoodsView.mGoodsTotalPrice);
        payDialog.setRadio(AllUtils.moneyCompare(mBalance, mBaseOrderGoodsView.mGoodsTotalPrice));
        payDialog.show();
    }

    private boolean show = false;
    public void setShow(){
        show = true;
    }

    @Override
    protected void onResume() {
        super.onResume();
        if(show){
            findViewById(R.id.act_buy_goods_ll).post(new Runnable() {
                public void run() {
                    AlipayH5Dialog accountCancelDialog = new AlipayH5Dialog(BuyGoodsActivity.this, new AlipayH5Dialog.OnCloseListener() {
                        @Override
                        public void confirm() {
//                            RouterUtils.toMain(BuyGoodsActivity.this, 4);
                            Intent intent = new Intent(BuyGoodsActivity.this, OrderActivity.class);
                            intent.putExtra("type", 1);
                            startActivity(intent);
                            finish();

                        }
                    });
                    accountCancelDialog.show();
                }
            });
            show = false;
        }
    }

    public void showSetPswDialog() {
        showSelectDialog(ResUtil.getString(R.string.my_tip),
                "为确保余额资金安全，请先设置千年艾支付密码"
                , "马上设置",
                "取消",
                new TipDialog.Dialogcallback() {
                    @Override
                    public void btnConfirm() {
                        SetPayPswActivity.start(BuyGoodsActivity.this);
                    }

                    @Override
                    public boolean cancel() {
                        return false;
                    }
                });
    }

    //支付密码弹窗
    public void showPsw() {
        if (pswInputDialog == null) {
            pswInputDialog = new PswInputDialog(context);
            pswInputDialog.setTextChangedListener(new PasswordView_1.TextChangedListener() {
                @Override
                public void textChanged(CharSequence changeText) {

                }

                @Override
                public void textCompleted(CharSequence text) {//余额支付
                    showLoading();
                    getP().pay(mPayOrderId, 0, 0,
                            (yoMoneyPay == 0 ? mPayMoney : mBaseOrderGoodsView.mGoodsTotalPrice),
                            mGoodsType == Type.GoodsType.GiveMore ? (mGoodsDetail.getProduct_type() + 1) : mGoodsDetail.getProduct_type(),
                            AESUtils.rsaEncrypt(text.toString()), yoMoneyPay);
                }
            });
        }
        pswInputDialog.show();
    }

    private void createOrder(int payType) {

        List<GoodsList> lists = new ArrayList<>();
        GoodsList goodsDetail = new GoodsList();
        goodsDetail.productId = mGoodsDetail.id;
        goodsDetail.num = goodsSize;
        lists.add(goodsDetail);
        String note = notesTv.getText().toString().trim();

        getP().getInterface(appInterfaceInfo.appInterface, mAddressInfo.getUserName(), mAddressInfo.getProvinceName(),
                mAddressInfo.getCityName(), mAddressInfo.getCountyName(), mAddressInfo.getProvinceName() +
                        mAddressInfo.getCityName() + mAddressInfo.getCountyName(), mAddressInfo.getMobile(), mAddressInfo.getAddress(),
                note, goodsSize, appInterfaceInfo.address, appInterfaceInfo.type, payType, new Gson().toJson(lists));
    }

    public void error(boolean pswError, String tip) {
        if (pswInputDialog != null) {
            pswInputDialog.showErrorTip(pswError, tip);
        } else {
            YMToast.showText(tip);
            if (pswInputDialog != null) {
                pswInputDialog.dismiss();
            }
        }
    }

    //
    public void error(String tip) {
        YMToast.showText(tip);
        if (pswInputDialog != null) {
            pswInputDialog.dismiss();
        }
    }


    //根据订单状态 跳到支付结果
    public void payResult(EventMessage eventMessage) {
        dismissLoading();
        if ("wxpay".equals(pay_type)) {
            TouchUtils.onBuyEvent(eventId,
                    UserInfoConfig.getRoleId(),
                    UserInfoConfig.getAgent(),
                    AllCode.Fail == eventMessage.getCode() ? "wx_pay_fail" : "wx_pay_success");
        }
        eventMessage.setGoodsType(mGoodsType);
        eventMessage.setMsg(mPayOrderId);
        eventMessage.setGoodsID(mGoodsDetail.getOidCardId());
        L.i("商品id：" + mGoodsDetail.getOidCardId());
        BuyResultActivity.Companion.start(BuyGoodsActivity.this, eventMessage);
        finish();
    }

    private void showCouponDialog() {
        UseCouponDialog useCouponDialog = new UseCouponDialog(this);
        useCouponDialog.setOnSelectListener((position, isUseCoupon) -> {

        });
        useCouponDialog.show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (Const.RequestCode.AddressCode == requestCode && data != null) {
            mAddressInfo = (AddressInfo) data.getSerializableExtra(Constant.DATA);
            L.i("地址：" + mAddressInfo.toString());
            mShowAddressView.setAddressInfo(mAddressInfo);
            mShowAddressView.showAddress();
//            getP().getAddress();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}
